using System;
using System.Text.RegularExpressions;
using System.Web;
using Quiki.ExpressionParsers;

namespace Quiki.ElementFormatters
{
    public class HeaderElementFormatter : ElementFormatterBase
    {
        public override bool FormatBegin(WikiTextElement element, HtmlFormatterContext context)
        {
            if (element.ElementType != WikiTextElementType.Heading)
                return false;

            context.CloseAllParagraphs();
            context.Writer.WriteLine();
            context.Writer.AddAttribute("id", FormatHeaderAnchorLink(element));
            context.Writer.RenderBeginTag("h" + element.Level);
            return true;
        }

        public override void FormatEnd (WikiTextElement element, HtmlFormatterContext context)
        {
            if (element.ElementType != WikiTextElementType.Heading)
                return;

            context.Writer.RenderEndTag ();
            context.Writer.WriteLine ();
        }

        public static string FormatHeaderAnchorLink (WikiTextElement headerElement)
        {
            // first replace all spaces with underscores
            string s = headerElement.Text.Replace(' ', '_');

            // now remove all invalid stuff
            s = invalidUriChars.Replace(s, String.Empty);

            // now encode the URL
            return HttpUtility.UrlEncodeUnicode(s);
        }

        private static readonly Regex invalidUriChars = new Regex("[^a-z0-9_]", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    }
}